package org.dbrd.preprocessor.xml;

import java.io.File;
import java.util.Iterator;

import org.dbrd.model.PrecessingBugReport;
import org.dom4j.Element;

public class MozillaXMLReportPreprocessor extends XMLReportPreprocessor {

	public MozillaXMLReportPreprocessor(File target, File reportDirectory, int firstReportId, int lastReportId) {
		super(target, reportDirectory, firstReportId, lastReportId);
	}

	@Override
	protected String getIssueRootTagName() {
		return "bug";
	}

	@Override
	protected String getIssueIdTagName() {
		return "bug_id";
	}

	@Override
	protected String getTimeTag() {
		return "bug_when";
	}

	protected String getTimeFormat() {
		return "yyyy-MM-dd HH:mm:ss Z";
	}
	
	private static final String ENHANCEMENT = "enhancement";
	
	@Override
	protected String getIssueType(Element issueElement) {
		String severity = ((Element) issueElement.elementIterator(getIssueTypeTagName()).next()).getText();
		if (ENHANCEMENT.equals(severity)) {
			return ENHANCEMENT;
		} else {
			return "defect";
		}
	}

	@Override
	protected int getPriority(Element issueElement) {
		String severity = ((Element) issueElement.elementIterator(getIssueTypeTagName()).next()).getText();
		if ("critical".equals(severity)) {
			return 1;
		} else if ("major".equals(severity)) {
			return 2;
		} else if ("normal".equals(severity)) {
			return 3;
		} else if ("minor".equals(severity)) {
			return 4;
		} else if ("trivial".equals(severity)) {
			return 5;
		} else if (ENHANCEMENT.endsWith(severity)) {
			return 6;
		} else {
			return 3;
			//throw new RuntimeException("Cannot reach here." + severity);
		}
	}

	@Override
	protected String getIssueTypeTagName() {
		return "bug_severity";
	}

	@Override
	protected String getSubComponentTagName() {
		return "component";
	}

	@Override
	protected String getComponentTagName() {
		return "product";
	}

	@SuppressWarnings("unchecked")
	@Override
	protected int getDuplicateId(Element issueElement) {
		
		for (Iterator<Element> iter = issueElement.elementIterator("dup_id"); iter.hasNext();) {
			Element ele = iter.next();
			return Integer.parseInt(ele.getText());
		}
		return PrecessingBugReport.NON_DUPLICATE;
	}
}
